<!-- src/views/CategoryListView.vue -->
<template>
  <div class="category-list-container" v-loading="loading">
    <el-page-header @back="$router.push('/')" content="所有板块" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <div v-if="!loading && categories.length === 0" class="no-categories">
      <p>暂无板块信息。</p>
    </div>

    <el-row :gutter="20" v-else>
      <el-col
        v-for="category in sortedCategories"
        :key="category.id"
        :span="24"
        :md="12"
        :lg="8"
      >
        <el-card
          class="category-card"
          shadow="hover"
          @click="$router.push(`/categories/${category.id}`)"
        >
          <div class="category-card-content">
            <div class="category-icon">
              <el-avatar
                v-if="category.iconUrl"
                :src="category.iconUrl"
                shape="square"
                :size="48"
              />
              <el-avatar v-else shape="square" :size="48" style="background-color: #409EFF;">
                {{ category.name.charAt(0).toUpperCase() }}
              </el-avatar>
            </div>
            <div class="category-info">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-description">{{ category.description }}</p>
              <div class="category-stats">
                <span class="stat-item">帖子数: {{ category.postCount || 0 }}</span>
                <span class="stat-item">今日: {{ category.todayPostCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 管理员操作区域 -->
    <div v-if="authStore.isAuthenticated && hasAdminPermission" class="admin-actions">
      <el-button type="primary" @click="$router.push('/categories/create')">
        创建新板块
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getCategories } from '@/services/categoryService';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const loading = ref(false);
const errorMessage = ref('');
const categories = ref([]);

// 计算属性：检查用户是否有管理员权限 (例如 CATEGORY_MANAGE)
const hasAdminPermission = computed(() => {
  // 1. 检查用户是否已认证
  if (!authStore.isAuthenticated) {
    console.log('hasAdminPermission: User not authenticated');
    return false;
  }

  // 2. 检查 currentUser 对象是否存在
  if (!authStore.currentUser) {
    console.log('hasAdminPermission: currentUser is null or undefined');
    return false;
  }

  // 3. 检查 currentUser 的 authorities 属性是否存在且为数组
  // 注意：这里假设 CustomUserDetails 实现了 UserDetails 接口，
  // 并且 getAuthorities() 返回的集合被 Pinia Store 正确序列化/反序列化为数组
  // 如果 CustomUserDetails 是自定义对象，可能需要检查 authStore.currentUser.roles...
  // 但根据之前的讨论和标准做法，通常是检查 Authentication.getAuthorities()
  // 在 Vue 组件中，我们访问的是 authStore.currentUser (CustomUserDetails 实例)
  // 所以需要检查 CustomUserDetails 实例上的 authorities 或者通过 getAuthorities() 方法
  // *** 最直接的方式是检查 authStore.currentUser.authorities ***
  const authorities = authStore.currentUser.authorities;

  if (!authorities || !Array.isArray(authorities)) {
    console.warn('hasAdminPermission: currentUser.authorities not found or not an array:', authorities);
    return false;
  }

  console.log('hasAdminPermission: User authorities:', authorities); // 调试日志

  // 4. 检查 authorities 数组中是否包含 'CATEGORY_MANAGE'
  // authorities 数组中的元素通常是 { authority: 'PERMISSION_NAME' } 这样的对象
  const hasPermission = authorities.some(auth => auth && auth.authority === 'CATEGORY_MANAGE');

  console.log('hasAdminPermission: Does user have CATEGORY_MANAGE?', hasPermission); // 调试日志

  return hasPermission;
});

// 计算属性：按 sortOrder 排序的板块列表
const sortedCategories = computed(() => {
  return [...categories.value].sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
});

// 获取所有板块列表
const fetchCategories = async () => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getCategories();
    categories.value = response.data || [];
  } catch (error) {
    console.error('Failed to fetch categories:', error);
    errorMessage.value = error.response?.data?.message || '获取板块列表失败';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.category-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.category-card {
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.category-card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.category-icon {
  margin-right: 20px;
}

.category-info {
  flex: 1;
}

.category-name {
  margin: 0 0 10px 0;
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
}

.category-description {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 0.9em;
  line-height: 1.4;
}

.category-stats {
  display: flex;
  justify-content: space-between;
  font-size: 0.85em;
  color: #999;
}

.stat-item {
  /* 可以添加样式 */
}

.no-categories {
  text-align: center;
  color: #999;
  font-size: 1.1em;
  margin-top: 50px;
}

.admin-actions {
  margin-top: 30px;
  text-align: center;
}
</style>
